var prefix = jsctx + "/member/gain";
var membergain = (function () {
    $('#exampleTable').on('load-success.bs.table', function (e, data) {
        if (data.total && !data.rows.length) {
            $('#exampleTable').bootstrapTable('selectPage').bootstrapTable('refresh');
        }
    });

    function reLoad() {
        $(".fixed-table-header-columns").css("display", "none");
        $(".fixed-table-body-columns").css("display", "none");
        $('#exampleTable').bootstrapTable('refresh');
    };

    function init() {
        setTimeout(function () {//防止先于-读取缓存执行
            load();
        }, 10)
    };
    var h = $(window).height() - 80;

    function load() {
        $('#exampleTable')
            .bootstrapTable({
                method: 'get',
                url: prefix + "/listPageMemberGain",
                iconSize: 'outline',
                toolbar: '#exampleToolbar',
                striped: false,
                dataType: "json",
                pagination: true,
                singleSelect: false,
                pageList: [10, 20, 30],
                pageSize: 10,
                pageNumber: 1,
                sidePagination: "server",
                cache: false,
                height: h,
                paginationShowPageGo: true,
                rightFixedColumns: false,
                showColumns: true,
                queryParams: function (params) {
                    return {
                        limit: params.limit,
                        offset: (params.offset / params.limit) + 1,
                        gainName: $("#gainName").val().trim(),
                        sublevel: $("#sublevel").val()
                    };
                },
                columns: [
                    {
                        field: 'memberGainId',
                        title: '序号',
                        width: '50', align: 'center',
                        formatter: function (value, row, index) {
                            return index + 1;
                        }
                    },
                     {field: 'gainName', title: '权益名称', align: 'center', width: '80'},
                    {field: 'memberLevel', title: '所属会员等级', align: 'center', width: '80'},
                    // {field: 'levelSubName', title: '所属会员子等级', width: '100', align: 'center'},
                    {field: 'levelSub', title: '所属会员子等级', width: '100', align: 'center'},
                    {field: 'gainExplain', title: '权益说明', width: '80', align: 'center'},
                    {
                        field: 'status', title: '状态', width: '250', align: 'center',
                        formatter: status_switch
                    },
                    {
                        field: 'isDefault', title: '是否默认', width: '100', align: 'center',
                        formatter: function (value, row, index) {
                            if (row.isDefault == '0') {
                                return '否';
                            }  else  {
                                return '是';
                            }
                        }
                    },
                    //0充值消费折扣 1充值赠送金额 2生日礼遇充值消费折扣  3生日礼遇充值送权益金  4.生日礼遇充值整单面 5.生日礼遇免单  6.生日礼遇满减. 默认0
                    {
                        field: 'gainType', title: '权益类型', width: '100', align: 'center',
                        formatter: function (value, row, index) {
                            if(row.gainType == '1'){
                                return '<span>充值赠送金额</span>';
                            } else if(row.gainType == '2'){
                                return '<span>生日礼遇充值消费折扣</span>';
                            } else if(row.gainType == '3'){
                                return '<span>生日礼遇充值送权益金</span>';
                            } else if(row.gainType == '4'){
                                return '<span>生日礼遇充值整单面</span>';
                            } else if(row.gainType == '5'){
                                return '<span>生日礼遇免单</span>';
                            } else if(row.gainType == '6'){
                                return '<span>生日礼遇满减</span>';
                            }  else  {
                                return '<span>充值消费折扣</span>';
                            }
                        }
                    },
                    {field: 'sort', title: '排序', width: '100', align: 'center'},
                    {
                        title: '操作',
                        field: 'orderId',
                        width: '200', align: 'center',
                        class: '',
                        formatter: function (value, row, index) {
                            var d = '<a class="btn btn-success btn-sm ' + has_edit + '" href="#" title="删除权益" onclick="membergain.deleteMemberGain(\''
                                + row.memberGainId
                                + '\')">删除</a> ';
                            var a = '<a class="btn btn-success btn-sm ' + has_edit + '" href="#" title="编辑权益" onclick="membergain.editMemberGain(\''
                                + row.memberGainId
                                + '\')">编辑</a> ';
                            var b = '';
                            var c = '';
                            var e = '';
                            var f = '';
                            // if (MemberManager_member_look) {
                            //     d = '<a class="btn btn-success btn-sm ' + has_edit + '" href="#" title="详情" onclick="member.detailMember(\''
                            //         + row.memberId
                            //         + '\')">详情</a> ';
                            //     a = '<a class="btn btn-primary btn-sm ' + has_edit + '" href="#" title="余额变动记录" onclick="member.memberAccountRecord(\''
                            //         + row.memberId
                            //         + '\')">余额变动记录</a> ';
                            //     f = '<a class="btn btn-primary btn-sm ' + has_edit + '" href="#" title="积分变动记录" onclick="member.integralAccountRecord(\''
                            //         + row.memberId
                            //         + '\')">积分变动记录</a> ';
                            // }
                            // if (MemberManager_member_update) {
                            //     b = '<a class="btn btn-danger btn-sm ' + has_edit + '" href="#" title="充值" onclick="member.recharge(\''
                            //         + row.memberId
                            //         + '\')">充值</a> ';
                            //     if (row.status == '0') {
                            //         c = '<a class="btn btn-danger btn-sm ' + has_edit + '" href="#" title="冻结" onclick="member.updateStatus(\''
                            //             + row.memberId
                            //             + '\')">冻结</a> ';
                            //
                            //     } else if (row.status == '1') {
                            //         c = '<a class="btn btn-info btn-sm ' + has_edit + '" href="#" title="解冻" onclick="member.updateStatus(\''
                            //             + row.memberId
                            //             + '\')">解冻</a> ';
                            //     }
                            //     e = '<a class="btn btn-danger btn-sm ' + has_edit + '" href="#" title="结束充电" onclick="member.updateChargeStatus(\''
                            //         + row.memberId
                            //         + '\')">结束充电</a> ';
                            // }
                            // if (row.chargeStatus == '1') {
                            //     return d + b + a + e + f;
                            // } else {
                            //     return d + b + a + c + f;
                            // }
                            return a+d;


                        }
                    }
                ] /*, onLoadSuccess: function () {
                    initSwitch();
                }, onPageChange: function () {
                    initSwitch();
                }*/
            });
    };

    function status_switch(value, row, index) {
        if (value == '0') {
            return  '<input class="tgl tgl-skewed" onclick="membergain.onSwitchChange(' + row.memberGainId +',1 )" id="cb'+row.memberGainId+'" type="checkbox">' +
                '<label class="tgl-btn" data-tg-off="启动" data-tg-on="禁用" for="cb'+row.memberGainId+'"></label>'
        } else {
            return '<input class="tgl tgl-skeweds"  onclick="membergain.onSwitchChange(' + row.memberGainId +',0 )" id="cb'+row.memberGainId+'" type="checkbox">' +
                '<label class="tgl-btn isok" data-tg-off="禁用" data-tg-on="启动" for="cb'+row.memberGainId+'"></label>'
        }
    }

    function onSwitchChange (isId, state) {
        //修改操作
        $.ajax({
            type: "post",
            dataType: "json",
            async: false,
            url: prefix + "/updateStatus",
            data: {
                status: state,
                id:isId
            },
            success: function (data) {
                reLoad();
            },
            error: function (xhr, error, exception) {
                let errorMsg = xhr.responseText;
                openMsg("error", "系统异常，" + errorMsg + "，请联系管理员！");
            }
        });
    }

   /* function initSwitch() {
        $("[name='role-status']").bootstrapSwitch({
            onText: "启用",      // 设置ON文本
            offText: "禁用",    // 设置OFF文本
            onColor: "primary",// 设置ON文本颜色(info/success/warning/danger/primary)
            offColor: "warning",  // 设置OFF文本颜色 (info/success/warning/danger/primary)
            size: "mini",    // 设置控件大小,从小到大  (mini/small/normal/large)
            hadleWidth: "10",
            // 当开关状态改变时触发
            onSwitchChange: function (event, state) {
                debugger
                //修改操作
                $.ajax({
                    type: "post",
                    dataType: "json",
                    async: false,
                    url: prefix + "/updateStatus",
                    data: {
                        status: state ? 0 : 1,
                        id: this.value
                    },
                    success: function (data) {
                        $('#TestTables').bootstrapTable('refresh'); //Table页面刷新
                    },
                    error: function (xhr, error, exception) {
                    }
                });
            }
        })
    }*/

    function deleteMemberGain(memberGainId) {
        layer.confirm('确定删除权益吗？', {
            btn: ['确定', '取消']
        }, function (index) {
            $.ajax({
                url: prefix + "/deleteMemberGain",
                type: "post",
                data: {
                    'memberGainId': memberGainId
                },
                success: function (data) {
                    layer.close(index);
                    if (data.status == 200) {
                        layer.msg("删除成功");
                        reLoad();
                    } else {
                        layer.msg(data.message);
                    }
                }
            });
        })
    }

    function addMemberGain() {
        location.href = prefix + "/addMemberGain";
    }


    function editMemberGain(memberGainId) {
        location.href = prefix + "/editMemberGain/" + memberGainId;
    }

    function updateStatus(memberId) {
        layer.confirm('确定要变更状态？', {
            btn: ['确定', '取消']
        }, function (index) {
            $.ajax({
                url: prefix + "/updateStatus",
                type: "post",
                data: {
                    'memberId': memberId
                },
                success: function (data) {
                    layer.close(index);
                    if (data.status == 200) {
                        layer.msg("变更成功");
                        reLoad();
                    } else {
                        layer.msg(data.message);
                    }
                }
            });
        })
    }

    function exportMemberInfo() {
        $.fileDownload(prefix + "/exportMemberInfo", { // 后台请求链接
            httpMethod: "get",　　　　　　　　// 请求方式
            contentType: 'application/json',　 // 请求头
            data: {　　　　　　　　　　　　　　　// 参数，左边为后台接收的参数名，右边为前端获取的值，
                gainName: $("#gainName").val().trim(),
              /*  memberType: $("#memberType").val().trim(),
                status: $("#status").val().trim(),
                chargeStatus: $("#chargeStatus").val().trim(),
                nickname: $("#nickname").val().trim(),
                remark: $("#remark").val().trim(),
                startTime: $("#startTime").val().trim(),
                endTime: $("#endTime").val().trim(),
                count: $("#count").val().trim() == '' ? 0 : $("#count").val().trim(),*/
                offset: $('.active .page-link').text(),
                limit: $(".page-size").text()
            },
            prepareCallback: function (url) {
                layer.msg("文件下载中...", {time: -1})
            },
            abortCallback: function (url) {
                // 异常终止
                layer.msg("文件下载异常！！");
            },
            successCallback: function (url) {
                layer.msg("文件下载成功！！", {time: 1500});
            },
            failCallback: function (data) {
                var str = "{" + data.substring(data.indexOf("{") + 1, data.indexOf("}")) + "}";
                layer.msg(JSON.parse(str).message);
            }
        })
    }

    return {
        init: init,
        reLoad: reLoad,
        addMemberGain: addMemberGain,
        deleteMemberGain: deleteMemberGain,
        onSwitchChange: onSwitchChange,
        editMemberGain: editMemberGain/*,
        detailMember: detailMember,
        exportMemberInfo: exportMemberInfo,
        updateChargeStatus: updateChargeStatus,
        integralAccountRecord: integralAccountRecord*/
    };
})();

var addMemberGain = (function () {
    function init() {
        validateRule();
    };

    var isajaxsend = true;

    function save() {
        //debugger
        if (isajaxsend) {
            //debugger
            var formData = new FormData($("#frmMemberGain")[0]);
            //获取权益类型
            /*var gainType = $("input[name='gainType']:checked").val();
            //获取table值
            if (gainType==0){
                var tableData = getValForString(gainType);
                formData.append("chargeRebateStr",JSON.stringify(tableData));
            }else if (gainType==1){
                var tableData = getValForString(gainType);
                formData.append("chargeHandselStr",JSON.stringify(tableData));
            }else{
                //
                var brithdayJson = {};
                brithdayJson.rebateTable  =  getValForString(0);
                brithdayJson.handselTable =  getValForString(1);
                formData.append("birthdayStr",JSON.stringify(brithdayJson));
            }*/
            $.ajax({
                cache: true,
                type: "POST",
                url: prefix + "/saveMemberGain",
                data: formData,
                processData: false,
                contentType: false,
                async: false,
                beforeSend: function () {
                    isajaxsend = false
                },
                error: function (request) {
                    parent.layer.alert("Connection error");
                },
                success: function (data) {
                    if (data.status == 200) {
                        parent.layer.msg("操作成功");
                        window.history.back();
                    } else {
                        parent.layer.alert(data.message)
                    }

                },
                complete: function () {
                    isajaxsend = false
                }
            });
        }
    }
    
   /* function getRedioVal(_name) {
        var radioValue;
        radioValue=document.getElementsByName(_name);
        if(radioValue!=null){
            var i;
            for(i=0;i<radioValue.length;i++){
                if(radioValue[i].checked){
                    return radioValue[i].value;
                }
            }
        }
        return null;
    }

    function getValForString(_val) {
        //debugger
        var list = [];

        if (_val==0){
            //获取到标签tr
            var trList = document.getElementById("bableId");//获取所有的table
            var rows = trList.rows;//获取所有行
            for(var i=1; i < rows.length; i++){
                var arr = {};
                var row = rows[i];//获取每一行
                arr["id"] = i;
                arr["rechargeAmount"] = row.cells[2].getElementsByTagName("INPUT")[0].value;
                arr["discountAmount"] = row.cells[3].getElementsByTagName("INPUT")[0].value;
                list.push(arr);
            }
        }else if (_val==1){
            //获取到标签tr
            var trList = document.getElementById("chargeHandselId");//获取所有的table
            var rows = trList.rows;//获取所有行
            for(var i=1; i < rows.length; i++){
                var arr = {};
                var row = rows[i];//获取每一行
                arr["id"] = i;
                arr["rechargeAmount"] = row.cells[2].getElementsByTagName("INPUT")[0].value;
                arr["gainAmount"] = row.cells[3].getElementsByTagName("INPUT")[0].value;
                arr["consumeUseAmount"] = row.cells[4].getElementsByTagName("INPUT")[0].value;
                list.push(arr);
            }
        }
        return list;
    }*/

    function validateRule() {
        var icon = "<i class='fa fa-times-circle'></i> ";
        $("#frmMemberGain").validate({
            rules: {
                gainName: {
                    required: true
                }, memberLevel: {
                    required: true
                }, levelSub: {
                    required: true
                }
            },
            messages: {
                gainName: {
                    required: icon + "请输入权益名称"
                }, memberLevel: {
                    required: icon + "请选择所属会员等级"
                }, levelSub: {
                    required: icon + "请选择会员子等级"
                }
            },
            submitHandler: function (form) {
                save();
            }
        })
    }

    return {
        init: init,
    };


})();

var saveMemberRemark = (function () {
    function init() {
        validateRule();
    };

    function getCheckedRoles() {
        var adIds = "";
        $("input:checkbox[name=role]:checked").each(function (i) {
            if (0 == i) {
                adIds = $(this).val();
            } else {
                adIds += ("," + $(this).val());
            }
        });
        return adIds;
    }

    var isajaxsend = true;

    function save() {
        if (isajaxsend) {
            var formData = new FormData($("#frmMember")[0]);
            $("#roleIds").val(getCheckedRoles());
            $.ajax({
                cache: true,
                type: "POST",
                url: prefix + "/saveMemberRemark",
                data: formData,
                processData: false,
                contentType: false,
                async: false,
                beforeSend: function () {
                    isajaxsend = false
                },
                error: function (request) {
                    parent.layer.alert("Connection error");
                },
                success: function (data) {
                    if (data.status == 200) {
                        parent.layer.msg("操作成功");
                        window.history.back();
                    } else {
                        parent.layer.alert(data.message)
                    }

                },
                complete: function () {
                    isajaxsend = false
                }
            });
        }
    }

    function validateRule() {
        var icon = "<i class='fa fa-times-circle'></i> ";
        $("#frmMember").validate({
            rules: {},
            messages: {},
            submitHandler: function (form) {
                save();
            }
        })
    }

    return {
        init: init
    };


})();
